<?php

namespace App\Common;

class Rsa
{
    use Singleton;

    private string $private_key;

    private string $public_key;


    public function __construct()
    {
        $this->private_key = BASE_PATH . '/config/private_key.pem';
        $this->public_key = BASE_PATH . '/config/public_key.pem';
    }


    /**
     * 获取私钥
     */
    private function getPrivateKey(): \OpenSSLAsymmetricKey|bool
    {
        $content = file_get_contents($this->private_key);
        return openssl_pkey_get_private($content);
    }

    /**
     * 获取公钥
     */
    private function getPublicKey(): \OpenSSLAsymmetricKey|bool
    {
        $content = file_get_contents($this->public_key);
        return openssl_pkey_get_public($content);
    }


    /**
     * 公钥加密
     * @param string $data
     * @return null|string
     */
    public function publicEncrypt(string $data = ''): ?string
    {
        if (!is_string($data)) {
            return null;
        }

        $publicKey = $this->getPublicKey();
        $encrypted_str = '';
        foreach (str_split($data, 117) as $v) {
            openssl_public_encrypt($v, $encrypted, $publicKey);
            $encrypted_str .= $encrypted;
        }

        return empty($encrypted_str) ? null : $encrypted_str;
    }

    /**
     * 私钥解密
     * @param string $key
     * @return string|null
     */
    public function privDecrypt(string $key = ''): ?string
    {
        if (!is_string($key)) {
            return null;
        }
        $privateKey = $this->getPrivateKey();
        $decrypted_str = '';
        foreach (str_split($key, 128) as $v) {
            openssl_private_decrypt($v, $decrypted, $privateKey);
            $decrypted_str .= $decrypted;
        }
        return empty($decrypted_str) ? null : $decrypted_str;
    }
}